// utils/ai-service.ts

import { AI_CONFIG, AIConfig, AIProvider } from '../config/ai-config';

/**
 * AI请求结果接口
 */
interface AIResponse {
  success: boolean;
  content: string;
  error?: string;
}

/**
 * 题目信息接口
 */
interface QuestionInfo {
  questionText: string;
  userAnswer: string;
  correctAnswer: string;
  userAnswerText: string;
  correctAnswerText: string;
}

/**
 * AI服务工具类
 * 支持多种AI服务提供商（DeepSeek、OpenAI、百度、阿里）
 */
export class AIService {
  private config: AIConfig;

  /**
   * 构造函数
   */
  constructor() {
    this.config = AI_CONFIG;
  }

  /**
   * 获取题目AI解释
   * @param questionInfo 题目信息
   * @returns Promise<AIResponse> AI解释结果
   */
  async explainQuestion(questionInfo: QuestionInfo): Promise<AIResponse> {
    if (!this.config.enabled) {
      return {
        success: false,
        content: 'AI解释功能未启用',
        error: 'AI功能已禁用'
      };
    }

    const prompt = this.buildPrompt(questionInfo);
    
    try {
      switch (this.config.currentProvider) {
        case 'deepseek':
          return await this.callDeepSeekAI(prompt);
        case 'openai':
          return await this.callOpenAI(prompt);
        case 'baidu':
          return await this.callBaiduAI(prompt);
        case 'alibaba':
          return await this.callAlibabaAI(prompt);
        default:
          throw new Error(`不支持的AI服务提供商: ${this.config.currentProvider}`);
      }
    } catch (error) {
      console.error('AI解释失败:', error);
      return {
        success: false,
        content: this.getFallbackExplanation(questionInfo),
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 构建提示词
   * @param questionInfo 题目信息
   * @returns string 构建的提示词
   */
  private buildPrompt(questionInfo: QuestionInfo): string {
    const { questionText, userAnswer, correctAnswer, userAnswerText, correctAnswerText } = questionInfo;
    
    return `题目：${questionText}

用户选择：${userAnswer}. ${userAnswerText}
正确答案：${correctAnswer}. ${correctAnswerText}

请按照系统提示的格式，详细解释这道题目。`;
  }

  /**
   * 调用DeepSeek AI API
   * @param prompt 提示词
   * @returns Promise<AIResponse> AI回复
   */
  private async callDeepSeekAI(prompt: string): Promise<AIResponse> {
    const config = this.config.deepseek;
    
    if (!config.apiKey || config.apiKey === 'YOUR_DEEPSEEK_API_KEY_HERE') {
      throw new Error('请在ai-config.ts中配置DeepSeek API Key');
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.baseUrl}/chat/completions`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.apiKey}`
        },
        data: {
          model: config.model,
          messages: [
            {
              role: 'system',
              content: this.config.systemPrompt
            },
            {
              role: 'user',
              content: prompt
            }
          ],
          max_tokens: config.maxTokens,
          temperature: config.temperature
        },
        success: (res: any) => {
          if (res.statusCode === 200 && res.data.choices && res.data.choices.length > 0) {
            resolve({
              success: true,
              content: res.data.choices[0].message.content
            });
          } else {
            reject(new Error(`DeepSeek API调用失败: ${res.statusCode}`));
          }
        },
        fail: (error: any) => {
          reject(new Error(`网络请求失败: ${error.errMsg || '未知错误'}`));
        }
      });
    });
  }

  /**
   * 调用OpenAI API
   * @param prompt 提示词
   * @returns Promise<AIResponse> AI回复
   */
  private async callOpenAI(prompt: string): Promise<AIResponse> {
    const config = this.config.openai;
    
    if (!config.apiKey || config.apiKey === 'YOUR_OPENAI_API_KEY_HERE') {
      throw new Error('请在ai-config.ts中配置OpenAI API Key');
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.baseUrl}/chat/completions`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.apiKey}`
        },
        data: {
          model: config.model,
          messages: [
            {
              role: 'system',
              content: this.config.systemPrompt
            },
            {
              role: 'user',
              content: prompt
            }
          ],
          max_tokens: config.maxTokens,
          temperature: config.temperature
        },
        success: (res: any) => {
          if (res.statusCode === 200 && res.data.choices && res.data.choices.length > 0) {
            resolve({
              success: true,
              content: res.data.choices[0].message.content
            });
          } else {
            reject(new Error('OpenAI API调用失败'));
          }
        },
        fail: (error: any) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 调用百度文心一言API
   * @param prompt 提示词
   * @returns Promise<AIResponse> AI回复
   */
  private async callBaiduAI(prompt: string): Promise<AIResponse> {
    const config = this.config.baidu;
    
    if (!config.apiKey || config.apiKey === 'YOUR_BAIDU_API_KEY_HERE') {
      throw new Error('请在ai-config.ts中配置百度API Key');
    }

    // 首先获取access_token
    const accessToken = await this.getBaiduAccessToken();
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.baseUrl}/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${config.model}?access_token=${accessToken}`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          messages: [
            {
              role: 'user',
              content: this.config.systemPrompt + '\n\n' + prompt
            }
          ]
        },
        success: (res: any) => {
          if (res.statusCode === 200 && res.data.result) {
            resolve({
              success: true,
              content: res.data.result
            });
          } else {
            reject(new Error('百度AI API调用失败'));
          }
        },
        fail: (error: any) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 获取百度AI的访问令牌
   * @returns Promise<string> 访问令牌
   */
  private async getBaiduAccessToken(): Promise<string> {
    const config = this.config.baidu;
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.baseUrl}/oauth/2.0/token`,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: `grant_type=client_credentials&client_id=${config.apiKey}&client_secret=${config.secretKey}`,
        success: (res: any) => {
          if (res.statusCode === 200 && res.data.access_token) {
            resolve(res.data.access_token);
          } else {
            reject(new Error('获取百度访问令牌失败'));
          }
        },
        fail: (error: any) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 调用阿里通义千问API
   * @param prompt 提示词
   * @returns Promise<AIResponse> AI回复
   */
  private async callAlibabaAI(prompt: string): Promise<AIResponse> {
    const config = this.config.alibaba;
    
    if (!config.apiKey || config.apiKey === 'YOUR_ALIBABA_API_KEY_HERE') {
      throw new Error('请在ai-config.ts中配置阿里API Key');
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.baseUrl}/services/aigc/text-generation/generation`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.apiKey}`
        },
        data: {
          model: config.model,
          input: {
            messages: [
              {
                role: 'system',
                content: this.config.systemPrompt
              },
              {
                role: 'user',
                content: prompt
              }
            ]
          }
        },
        success: (res: any) => {
          if (res.statusCode === 200 && res.data.output && res.data.output.text) {
            resolve({
              success: true,
              content: res.data.output.text
            });
          } else {
            reject(new Error('阿里AI API调用失败'));
          }
        },
        fail: (error: any) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 获取备用解释（当AI服务不可用时）
   * @param questionInfo 题目信息
   * @returns string 备用解释
   */
  private getFallbackExplanation(questionInfo: QuestionInfo): string {
    const { questionText, correctAnswer, correctAnswerText } = questionInfo;
    
    return `📚 题目解析

📝 题目：${questionText}

✅ 正确答案：${correctAnswer}. ${correctAnswerText}

💡 温馨提示：
当前AI解释服务暂时不可用，建议您：

1. 🔍 仔细回顾题目中的关键信息
2. 💭 理解正确答案的逻辑和原理  
3. 📖 查阅相关资料加深理解
4. 🔄 多做类似题目巩固知识点
5. 👨‍🏫 请教老师或同学获得详细解释

📱 如需AI智能解释，请：
- 检查网络连接是否正常
- 确认API配置是否正确
- 稍后重试或联系管理员

继续加油，相信你一定能掌握这个知识点！ 💪`;
  }

  /**
   * AI对话功能
   * @param chatRequest 对话请求
   * @returns Promise<AIResponse> AI回复
   */
  async chatWithAI(chatRequest: { messages: any[], context?: string }): Promise<AIResponse> {
    if (!this.config.enabled) {
      return {
        success: false,
        error: 'AI解释功能已关闭',
        content: ''
      };
    }

    try {
      // 构建对话提示词
      const conversationPrompt = this.buildChatPrompt(chatRequest.messages, chatRequest.context);
      
      // 根据当前配置的AI服务商调用相应的API
      switch (this.config.currentProvider) {
        case 'deepseek':
          return await this.callDeepSeekChat(conversationPrompt);
        case 'openai':
          return await this.callOpenAIChat(conversationPrompt);
        case 'baidu':
          return await this.callBaiduChat(conversationPrompt);
        case 'alibaba':
          return await this.callAlibabaChat(conversationPrompt);
        default:
          throw new Error(`不支持的AI服务商: ${this.config.currentProvider}`);
      }
    } catch (error) {
      console.error('AI对话服务调用失败:', error);
      
      return {
        success: false,
        error: error instanceof Error ? error.message : '未知错误',
        content: this.getFallbackChatResponse()
      };
    }
  }

  /**
   * 构建对话提示词
   * @param messages 对话消息
   * @param context 上下文信息
   * @returns string 构建的提示词
   */
  private buildChatPrompt(messages: any[], context?: string): string {
    let prompt = this.config.systemPrompt + '\n\n';
    
    if (context) {
      prompt += `上下文信息：\n${context}\n\n`;
    }
    
    prompt += '对话历史：\n';
    messages.forEach(msg => {
      const role = msg.role === 'user' ? '用户' : 'AI助手';
      prompt += `${role}：${msg.content}\n`;
    });
    
    return prompt;
  }

  /**
   * 调用DeepSeek对话API
   * @param prompt 提示词
   * @returns Promise<AIResponse> AI回复
   */
  private async callDeepSeekChat(prompt: string): Promise<AIResponse> {
    const config = this.config.deepseek;
    
    if (!config.apiKey || config.apiKey === 'YOUR_DEEPSEEK_API_KEY_HERE') {
      throw new Error('请在ai-config.ts中配置DeepSeek API Key');
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.baseUrl}/chat/completions`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.apiKey}`
        },
        data: {
          model: config.model,
          messages: [
            {
              role: 'user',
              content: prompt
            }
          ],
          max_tokens: config.maxTokens,
          temperature: config.temperature
        },
        success: (res: any) => {
          if (res.statusCode === 200 && res.data.choices && res.data.choices.length > 0) {
            resolve({
              success: true,
              content: res.data.choices[0].message.content
            });
          } else {
            reject(new Error('DeepSeek API调用失败'));
          }
        },
        fail: (error: any) => {
          reject(error);
        }
      });
    });
  }

  /**
   * 调用OpenAI对话API
   * @param prompt 提示词
   * @returns Promise<AIResponse> AI回复
   */
  private async callOpenAIChat(prompt: string): Promise<AIResponse> {
    return this.callOpenAI(prompt); // 复用现有的OpenAI方法
  }

  /**
   * 调用百度对话API
   * @param prompt 提示词
   * @returns Promise<AIResponse> AI回复
   */
  private async callBaiduChat(prompt: string): Promise<AIResponse> {
    return this.callBaiduAI(prompt); // 复用现有的百度方法
  }

  /**
   * 调用阿里对话API
   * @param prompt 提示词
   * @returns Promise<AIResponse> AI回复
   */
  private async callAlibabaChat(prompt: string): Promise<AIResponse> {
    return this.callAlibabaAI(prompt); // 复用现有的阿里方法
  }

  /**
   * 获取备用对话回复（当AI服务不可用时）
   * @returns string 备用回复
   */
  private getFallbackChatResponse(): string {
    return `🤖 抱歉，AI助手暂时无法回复您的问题。

🔧 可能的原因：
• 网络连接不稳定
• AI服务暂时繁忙
• API配置需要检查

💡 建议您：
• 检查网络连接
• 稍后重试
• 查看错题详情进行自主分析

📚 学习小贴士：
• 仔细阅读题目要求
• 分析正确答案的逻辑
• 总结知识点和解题方法
• 多做类似题目巩固

继续加油学习！💪`;
  }

  /**
   * 更新AI配置
   * @param newConfig 新配置
   */
  updateConfig(newConfig: Partial<AIConfig>): void {
    this.config = { ...this.config, ...newConfig };
  }

  /**
   * 获取当前配置
   * @returns AIConfig 当前配置
   */
  getConfig(): AIConfig {
    return { ...this.config };
  }
} 